package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.user.request.UserBanRequest;
import com.blog.cmrpersonalblog.entity.UserBan;
import com.blog.cmrpersonalblog.service.UserBanService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 用户禁言管理控制器
 * 提供用户禁言和解禁功能
 */
@Slf4j
@RestController
@RequestMapping("/admin/user-ban")
@CrossOrigin(origins = "*", maxAge = 3600)
@SaCheckRole("admin")
@Validated
public class UserBanController {

   @Resource
    private UserBanService userBanService;

    /**
     * 禁言用户
     */
    @PostMapping("/ban")
    public Result<Void> banUser(@RequestBody @Valid UserBanRequest banRequest) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员禁言用户: request={}, operatorId={}", banRequest, operatorId);
        
        try {
            boolean success = userBanService.banUser(banRequest, operatorId);
            if (success) {
                return Result.success("用户禁言成功");
            } else {
                return Result.error("用户禁言失败");
            }
        } catch (Exception e) {
            log.error("禁言用户失败", e);
            return Result.error("禁言失败：" + e.getMessage());
        }
    }

    /**
     * 解除用户禁言
     */
    @PostMapping("/unban")
    public Result<Void> unbanUser(@RequestParam @NotNull Long userId, 
                                 @RequestParam @NotNull String banType) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员解除禁言: userId={}, banType={}, operatorId={}", userId, banType, operatorId);
        
        try {
            boolean success = userBanService.unbanUser(userId, banType, operatorId);
            if (success) {
                return Result.success("解除禁言成功");
            } else {
                return Result.error("解除禁言失败");
            }
        } catch (Exception e) {
            log.error("解除禁言失败", e);
            return Result.error("解除禁言失败：" + e.getMessage());
        }
    }

    /**
     * 批量解除禁言
     */
    @PostMapping("/batch-unban")
    public Result<Integer> batchUnbanUsers(@RequestParam List<Long> userIds, 
                                          @RequestParam @NotNull String banType) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员批量解除禁言: userIds={}, banType={}, operatorId={}", userIds, banType, operatorId);
        
        try {
            int count = userBanService.batchUnbanUsers(userIds, banType, operatorId);
            return Result.success("批量解除禁言成功", count);
        } catch (Exception e) {
            log.error("批量解除禁言失败", e);
            return Result.error("批量解除禁言失败：" + e.getMessage());
        }
    }

    /**
     * 检查用户是否被禁言
     */
    @GetMapping("/check")
    public Result<Boolean> checkUserBan(@RequestParam @NotNull Long userId, 
                                       @RequestParam @NotNull String banType) {
        log.info("检查用户禁言状态: userId={}, banType={}", userId, banType);
        try {
            boolean isBanned = userBanService.isUserBanned(userId, banType);
            return Result.success(isBanned);
        } catch (Exception e) {
            log.error("检查用户禁言状态失败", e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户禁言状态
     */
    @GetMapping("/status/{userId}")
    public Result<Map<String, Object>> getUserBanStatus(@PathVariable @NotNull Long userId) {
        log.info("获取用户禁言状态: userId={}", userId);
        try {
            Map<String, Object> status = userBanService.getUserBanStatus(userId);
            return Result.success(status);
        } catch (Exception e) {
            log.error("获取用户禁言状态失败", e);
            return Result.error("获取状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户生效中的禁言记录
     */
    @GetMapping("/active/{userId}")
    public Result<List<UserBan>> getActiveBans(@PathVariable @NotNull Long userId) {
        log.info("获取用户生效中的禁言记录: userId={}", userId);
        try {
            List<UserBan> activeBans = userBanService.getActiveBans(userId);
            return Result.success(activeBans);
        } catch (Exception e) {
            log.error("获取生效中的禁言记录失败", e);
            return Result.error("获取记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户禁言历史
     */
    @GetMapping("/history/{userId}")
    public Result<List<UserBan>> getUserBanHistory(@PathVariable @NotNull Long userId) {
        log.info("获取用户禁言历史: userId={}", userId);
        try {
            List<UserBan> history = userBanService.getUserBanHistory(userId);
            return Result.success(history);
        } catch (Exception e) {
            log.error("获取用户禁言历史失败", e);
            return Result.error("获取历史失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询禁言记录
     */
    @GetMapping("/records")
    public Result<IPage<UserBan>> getBanRecords(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String banType,
            @RequestParam(required = false) Integer status) {
        log.info("分页查询禁言记录: current={}, size={}, userId={}, banType={}, status={}", 
                current, size, userId, banType, status);
        try {
            IPage<UserBan> pageResult = userBanService.getBanRecords(current, size, userId, banType, status);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询禁言记录失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 延长禁言时间
     */
    @PostMapping("/extend/{banId}")
    public Result<Void> extendBanTime(@PathVariable @NotNull Long banId, 
                                     @RequestParam @NotNull Integer additionalMinutes) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员延长禁言时间: banId={}, additionalMinutes={}, operatorId={}", 
                banId, additionalMinutes, operatorId);
        
        try {
            boolean success = userBanService.extendBanTime(banId, additionalMinutes, operatorId);
            if (success) {
                return Result.success("延长禁言时间成功");
            } else {
                return Result.error("延长禁言时间失败");
            }
        } catch (Exception e) {
            log.error("延长禁言时间失败", e);
            return Result.error("延长失败：" + e.getMessage());
        }
    }

    /**
     * 自动解除过期禁言
     */
    @PostMapping("/auto-unban")
    public Result<Integer> autoUnbanExpiredBans() {
        log.info("管理员触发自动解除过期禁言");
        try {
            int count = userBanService.autoUnbanExpiredBans();
            return Result.success("自动解除过期禁言完成", count);
        } catch (Exception e) {
            log.error("自动解除过期禁言失败", e);
            return Result.error("自动解除失败：" + e.getMessage());
        }
    }

    /**
     * 获取即将到期的禁言记录
     */
    @GetMapping("/expiring")
    public Result<List<UserBan>> getExpiringBans(@RequestParam(defaultValue = "60") Integer beforeMinutes) {
        log.info("获取即将到期的禁言记录: beforeMinutes={}", beforeMinutes);
        try {
            List<UserBan> expiringBans = userBanService.getExpiringBans(beforeMinutes);
            return Result.success(expiringBans);
        } catch (Exception e) {
            log.error("获取即将到期的禁言记录失败", e);
            return Result.error("获取记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取禁言统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getBanStatistics() {
        log.info("管理员查看禁言统计信息");
        try {
            Map<String, Object> statistics = userBanService.getBanStatistics();
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取禁言统计信息失败", e);
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取禁言类型分布
     */
    @GetMapping("/type-distribution")
    public Result<Map<String, Long>> getBanTypeDistribution() {
        log.info("管理员查看禁言类型分布");
        try {
            Map<String, Long> distribution = userBanService.getBanTypeDistribution();
            return Result.success(distribution);
        } catch (Exception e) {
            log.error("获取禁言类型分布失败", e);
            return Result.error("获取类型分布失败：" + e.getMessage());
        }
    }

    /**
     * 获取最近禁言记录
     */
    @GetMapping("/recent")
    public Result<List<UserBan>> getRecentBans(@RequestParam(defaultValue = "10") Integer limit) {
        log.info("管理员查看最近禁言记录: limit={}", limit);
        try {
            List<UserBan> recentBans = userBanService.getRecentBans(limit);
            return Result.success(recentBans);
        } catch (Exception e) {
            log.error("获取最近禁言记录失败", e);
            return Result.error("获取记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户禁言次数
     */
    @GetMapping("/count/{userId}")
    public Result<Integer> getUserBanCount(@PathVariable @NotNull Long userId) {
        log.info("获取用户禁言次数: userId={}", userId);
        try {
            int count = userBanService.getUserBanCount(userId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取用户禁言次数失败", e);
            return Result.error("获取次数失败：" + e.getMessage());
        }
    }

    /**
     * 获取操作人的禁言操作记录
     */
    @GetMapping("/operations/{operatorId}")
    public Result<List<UserBan>> getBanOperationsByOperator(
            @PathVariable @NotNull Long operatorId,
            @RequestParam(defaultValue = "20") Integer limit) {
        log.info("获取操作人的禁言操作记录: operatorId={}, limit={}", operatorId, limit);
        try {
            List<UserBan> operations = userBanService.getBanOperationsByOperator(operatorId, limit);
            return Result.success(operations);
        } catch (Exception e) {
            log.error("获取操作记录失败", e);
            return Result.error("获取操作记录失败：" + e.getMessage());
        }
    }

    /**
     * 验证禁言请求
     */
    @PostMapping("/validate")
    public Result<String> validateBanRequest(@RequestBody @Valid UserBanRequest banRequest) {
        log.info("验证禁言请求: {}", banRequest);
        try {
            String validationResult = userBanService.validateBanRequest(banRequest);
            if (validationResult == null) {
                return Result.success("验证通过");
            } else {
                return Result.error(validationResult);
            }
        } catch (Exception e) {
            log.error("验证禁言请求失败", e);
            return Result.error("验证失败：" + e.getMessage());
        }
    }
}
